<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SchoolApi } from '#/api/edu/base/school';
import type { EduSchoolContactApi } from '#/api/edu/base/schoolContact';

import { defineEmits, ref, watch } from 'vue';

import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';

import { useContactDetailGridColumns } from '../data';

const props = defineProps<{
  desensitize: boolean;
  school: SchoolApi.School;
  showDesensitizeButton: boolean;
}>();
const emit = defineEmits(['changeDesensitize']);
const contactList = ref<EduSchoolContactApi.SchoolContact[]>([]);
const index = ref<number>(0);

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    id: 'schoolContact-grid-school-detail',
    columns: useContactDetailGridColumns(),
    minHeight: 300,
    pagerConfig: {
      enabled: false,
    },
    keepSource: true,
    data: [] as EduSchoolContactApi.SchoolContact[],
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EduSchoolContactApi.SchoolContact>,
});

function handleDesensitize() {
  emit('changeDesensitize');
}
watch(
  () => props.school.contacts,
  (newValue) => {
    // 如果已经是数组，直接使用；如果是字符串，解析后使用
    const data = Array.isArray(newValue)
      ? newValue
      : JSON.parse(newValue || '[]');

    data.forEach((item) => {
      if (!item.id) {
        index.value = index.value - 1;
        item.id = index.value;
      }
    });
    contactList.value = data;
    gridApi.setGridOptions({ data });
  },
  { immediate: true },
);
</script>

<template>
  <Grid table-title="学校负责人信息">
    <template #toolbar-tools>
      <TableAction
        v-if="showDesensitizeButton"
        :actions="[
          {
            label: desensitize ? '关闭脱敏' : '启用脱敏',
            type: 'primary',
            danger: desensitize,
            icon: desensitize
              ? 'ant-design:eye-filled'
              : 'ant-design:eye-invisible-filled',
            auth: ['edu:base:admin-department:query'],
            onClick: handleDesensitize,
          },
        ]"
      />
    </template>
  </Grid>
</template>
